<?php
/**
 @prefix : <http://purl.org/net/ns/doas#> .
 @about: "<app/controllers/users_controller.php>", a: ":PHPScript",
 :shortdesc "This is a MML Tracks placeholder class.";
 :author [:name "Logue"; :homepage <http://logue.be/> ];
 :license <http://www.gnu.org/licenses/gpl-3.0.html>;
 :dependencies "none" .
*/
// Lorelei Users placeholder class
// Copyright (c)2008 Logue <http://logue.be/> All rights reserved.

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

// based on Bakery.

class UsersController extends AppController {
	var $name = 'Users';
	var $helpers = array('Html', 'Form');
	var $components = array('Auth','Email','Cookie');

	//beforeFilterにログインしなくても良いactionを指定
	function beforeFilter() {
		$this->Auth->allow('register','reminder','view','openid');
	}

	//ログイン
	function login(){
		if ($this->Auth->isAuthorized()){
			// ログイン済みの場合
			$this->Session->setFlash(__('You have already logged in.', true));
			$this->redirect($this->Auth->redirect());
		}
		$this->pageTitle = __('Login',true);
		$this->set('user',$this->Cookie->read('Auth.User'));
	}

	//ログアウト
	function logout(){
//		$this->Cookie->del('Auth.User');
//		$this->pageTitle = __('Logout',true);
		$this->Auth->logout();
		$this->redirect('/');
		$this->Session->setFlash(__('You have been logout.', true));
	}

	//ユーザ追加
	function add($register = null) {
		$this->pageTitle = __('User Registration',true);

		if ($this->Auth->isAuthorized()){
			// ログイン済みの場合
			$this->Session->setFlash(__('You have already logged in.', true));
			$this->redirect($this->Auth->redirect());
		}else{
			if (!empty($this->data)) {
				if (isset($this->data['User']['id'])) unset($this->data['User']['id']);
				
				$email = $this->data['User']['email'];
				if(empty($email)) {
					$this->Session->setFlash('Please enter an email.');
					$this->set('error',array('email_missing' => true));
					$this->render(); exit;
				}

				$token = $this->User->__generateToken();
				$this->data['User']['email_token'] = $token;

				$sixtyMins = time() + 43000;
				$this->data['User']['email_token_expires'] = date('Y-m-d H:i:s', $sixtyMins);

				$this->User->create();
				// 保存処理
				if ($this->User->save($this->data)){
					//メールを送信
					$this->Email->to = $email;
					$this->Email->charset='utf-8';
					$this->Email->from = 'Lorelei <mabinogi@logue.be>';
					$this->Email->replyTo = 'Lorelei New Account <mabinogi@logue.be>';
					$this->Email->return = '<mabinogi@logue.be>';
					$this->Email->subject = __('Lorelei',true).' '.__('Account Created', true);
					$this->Email->template = null;

					$content[] = __('To validate your account on The Lorelei, you must vist the URL below within 12 hours',true);
					$content[] = Router::url('/users/verify/email/'.$this->data['User']['email_token'], true);
					$this->Email->send($content);

					$this->Session->setFlash(__('Your account has been created. You should receive an email shortly to authenticate your account. Once validated you will be able to login', true));
					$this->redirect(array('action'=>'login'));
				} else {
					$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), __('User',true)));
				}
			}else{
				$this->Session->setFlash(__('The wrong value is included.',true));	// データーバリテーション
			}
		}
	}
	
	function view($id) {
		$this->redirect(array('controller'=>'articles','action'=>'user',$id));
	}

	function register() {
		$this->setAction('add');
	}

/*************************************************************************************************/
	// パスワード再発行
	function reminder() {
		if ($this->Auth->isAuthorized()){
			// ログイン済みの場合
			$this->Session->setFlash(__('You have already logged in.', true));
			$this->redirect($this->Auth->redirect());
		}else{
			if(empty($this->data)) {
				$this->render();
			} else {
				$email = $this->data['User']['email'];

				if ($this->User->findCount(array('User.email' => $this->data['User']['email'])) === '0') {
					$this->User->invalidate('email');
					$this->Session->setFlash(__('Please correct errors below.', true));
					$this->render();
				} else {
					$this->User->_saveTemp($this->data['User']['email']);
					$this->User->recursive = '-1';
					$token = $this->User->find(array('User.email' => $email), 'email_token');

					$this->Email->to = $email;
					$this->Email->charset='utf-8';
					$this->Email->from = 'Lorelei Password Reminder <mabinogi@logue.be>';
					$this->Email->replyTo = 'Lorelei Password Reminder <mabinogi@logue.be>';
					$this->Email->return = '<mabinogi@logue.be>';
					$this->Email->subject = 'Lorelei Password Reminder URL';
					$this->Email->template = null;

					$content[] = __('A request to reset you password has been submitted.',true);
					$content[] = __('Please visit the following url to have your temporary password sent.',true);
					$content[] = Router::url('/users/verify/reset/'.$user['User']['email_token'], true);
					$this->Email->send($content);
					$this->Session->setFlash(__('You should receive an email with further instruction shortly.', true));
					$this->redirect('/');
				}
			}
		}
	}

	// メールチェック
	function verify($type = 'email') {
		if(isset($this->passedArgs['1'])){
			$token = $this->passedArgs['1'];
		} else {
			$this->Session->setFlash('Invalid verification token.');
			$this->render(); exit;
		}
		if($type === 'email') {
			$data = $this->User->validateToken($token);
		} elseif($type === 'reset') {
			$data = $this->User->validateToken($token, true);
		} else {
			$this->Session->setFlash('There url you accessed is no longer valid');
			$this->redirect(array('action' => 'login'));
		}

		$password = $data['User']['psword'];
		$data = $this->Auth->hashPasswords($data);

		if($data !== false){
			$email = $data['User']['email'];
			unset($data['User']['email']);
			if($this->User->save($data, false)) {
				if($type === 'reset'){
			        $this->Email->to = $email;
					$this->Email->from = Configure::read('Site.email');
					$this->Email->subject = Configure::read('Site.name') . ' password reset' ;
					$this->Email->template = null;
					$content[] = __('Your password has been reset',true);
					$content[] = __('Please login using',true);
					$content[] = __('Username',true) . ': ' . $data['User']['username'];
					$content[] = __('Password',true) . ': ' . $password;
					$this->Email->send($content);
					$this->Session->setFlash('Your password was sent to your registered email account');
				} else {
					$this->Session->setFlash('Your Email was validated, Please Login');
					$this->redirect(array('action' => 'login'));
				}
			} else {
				$this->Session->setFlash('There was an error trying to validate, check your email and the url entered');
			}
		} else {
			$this->Session->setFlash('There url you accessed is no longer valid');
			$this->redirect(array('action' => 'login'));
		}
	}
	
	function mabichara($id = null){
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Article',true)));
		}
		// データー取得
		$user = $this->User->read(null, $id);
		if($user){
			$this->set('user', $user);
		}else{
			$this->cakeError('error404');
		}
	}
}
?>